#Survival

#library packages
library(ggplot2)
library(dplyr)
library(survival)
library(survminer)
library(data.table)

#import source data
expr<-fread(file = './Analysis-survival/Gepliver_surv_expr.txt',data.table = F,sep = '\t')
rownames(expr)<-expr$gene
expr<-expr[,-1]
icc.expr<-fread(file = './Analysis-Survival/fudan_icc_surv_expr.txt',data.table = F,sep = '\t')
rownames(icc.expr)<-icc.expr$gene
icc.expr<-icc.expr[,-1]
surv<-read.table('./Analysis-Survival/Gepliver_surv_all.txt',header = T,sep = '\t')

#dim parameters
gene<-'TRIM71'
tumor.type<-'HCC' #choose one from c('HCC','ICC')
dataset<-unique(surv$Dataset_size)[1] #choose one from datasets
surv.data<-'OS' #choose one from c('OS','DSS','DFS','PFS')
surv.event<-paste(surv.data,'.event',sep = '')
up.cut<-'Median' #choose one from c('Median','Quantile (75%)') or input customized percent value
low.cut<-'Median' #choose one from c('Median','Quantile (25%)') or input customized percent value
choice<-list(tumor.type,dataset,surv.data,surv.event,up.cut,low.cut)
names(choice)<-c('tumor.type','dataset','surv.data','surv.event','up.cut','low.cut')
choice$up.cut<-ifelse(choice$up.cut=='Median',50,ifelse(choice$up.cut=='Quantile (75%)',75,choice$up.cut))
choice$low.cut<-ifelse(choice$low.cut=='Median',50,ifelse(choice$low.cut=='Quantile (25%)',25,choice$low.cut))

#extract data
if (choice$dataset == 'Fudan_ICC(n=244)'){
  expr.use<-icc.expr
} else {
  expr.use<-expr
}
if (gene %in% rownames(expr.use)) {
  expr.gene<-expr.use[gene,]
} else {
  print('The gene does not exist in the dataset selected.')
}
sample<-surv$Run[(surv$Tumor== choice$tumor.type) & 
                   (surv$Dataset_size %in% choice$dataset) &
                   !is.na(surv[,choice$surv.data]) & !is.na(surv[,choice$surv.event])]
surv.filter<-surv[match(sample,surv$Run,nomatch = 0),]
surv.filter<-mutate(surv.filter,expr = as.numeric(expr.gene[,sample]))
surv.filter<-mutate(surv.filter,group = ifelse(expr>quantile(expr,as.numeric(choice$up.cut)/100),1,0))
surv.filter<-as.data.frame(surv.filter[!is.na(surv.filter$group),])

#plot
a<-which(colnames(surv.filter)==choice$surv.data)
b<-which(colnames(surv.filter)==choice$surv.event)
fit<-survfit(Surv(surv.filter[,a],surv.filter[,b])~group,data = surv.filter)
sum<-summary(coxph(Surv(surv.filter[,choice$surv.data],surv.filter[,choice$surv.event])~group,data = surv.filter))
anno<-paste("HR(High) =",round(sum$coefficients[,2],2),"\np =",round(sum$coefficients[,5],2),collapse = '')
p<-ggsurvplot(fit,pval = F,conf.int = F,
               legend.title="",legend.labs=c('Low group','High group'),#
               risk.table=T, xlab=paste(choice$surv.data,' (Days)'), palette = c('#3288BD','#D53E4F'),
               ggtheme = theme_classic())
p$plot<-p$plot+annotate('text',x=0,y=0.17,label=anno,size=3.5,hjust = 0)+labs(title = gene)+theme(plot.title = element_text(hjust = 0.5))
png(file="survival.png",width=2000,height=2000,res=300)
print(p)
dev.off()
